#include "topo.h"
#include "queue"
#include <fstream>
#include "widget.h"
topo::topo(QWidget *parent)
    : QWidget{parent}
{

}

const int N=105;
int mysize;
std::vector<int> e[N],g[N];
int din[N];
std::vector<int> tp;
std::vector<std::pair<std::string,int>> list0;
std::vector<std::string> list3;

std::vector<std::string> topo::split(std::string& str, char delimiter) {
    std::vector<std::string> result;
    size_t start = 0;
    size_t end = str.find(delimiter);

    while (end != std::string::npos) {
        result.push_back(str.substr(start, end - start));
        start = end + 1;
        end = str.find(delimiter, start);
    }

    result.push_back(str.substr(start, end));
    return result;
}


void topo::prepare(){
    //待转化
    Widget *w=new Widget;
    QStringList Qlist0 = w->getTableViewData(0);
    QStringList Qlist1 = w->getTableViewData(1);
    QStringList Qlist3 = w->getTableViewData(3);
    list0.push_back(std::make_pair("kid",0));
    list3.push_back("kid");
    for (int i = 0; i < Qlist0.size(); ++i) {
        list0.push_back(std::make_pair(Qlist0[i].toStdString(), Qlist1[i].toInt()));
        list3.push_back(Qlist3[i].toStdString());
    }

    mysize=list0.size();
    for(unsigned long long i=1;i<list3.size();i++){
        std::string s=list3[i];
        std::vector<std::string> temp = split(s,'-');
        for(unsigned long long j=0;j<temp.size();j++){
            int x=stoi(temp[j]);
            e[i].push_back(x);
        }
    }
    for(int i=1;i<(int)list3.size();i++){
        for(int j=0;j<(int)e[i].size();j++){
            if(e[i][j]!=0){
                g[e[i][j]].push_back(i);
            }
        }
        if(e[i][0] != 0) din[i]=e[i].size();
    }

    delete w;
}

void topo::toposort(){
    topo::prepare();
    std::queue<int> q;
    for(int i=1;i<mysize;i++)
        if(din[i]==0) q.push(i);
    while(q.size()){
        int x=q.front();q.pop();
        tp.push_back(x);
        for(auto i:g[x]){
            if(--din[i]==0) q.push(i);
        }
    }

    //找到文件的存储路径
    QString workingDirectory = QDir::toNativeSeparators(QDir::current().filePath("output.txt"));
    std::string work=workingDirectory.toStdString();
    std::ofstream outFile(work); // 创建一个输出文件流，打开文件 myfile.txt
    if (outFile.is_open()) { // 检查文件是否成功打开
        for(int i=0;i<(int)tp.size();i++){
            std::string st=list0[tp[i]].first +","+std::to_string(list0[tp[i]].second);
            outFile << st; // 将myString写入文件
            outFile << "\n";
        }
        outFile.close(); // 关闭文件
    }

    //clear
    mysize = 0;
    for(int i = 0; i < N; i++) {
        e[i].clear();
        g[i].clear();
        din[i] = 0;
    }
    list0.clear();
    list3.clear();
    tp.clear();
}














